package com.ewzj.bigdata.mvp.presenter

import android.app.Activity
import android.app.Application
import android.util.Log
import com.ewzj.bigdata.R
import com.ewzj.bigdata.app.config.AppKey
import com.ewzj.bigdata.app.extensions.DelegatesExt
import com.ewzj.bigdata.app.utils.RegExpValidatorUtils
import com.ewzj.bigdata.app.utils.RxUtils
import com.ewzj.bigdata.mvp.contract.LoginContract
import com.ewzj.bigdata.mvp.model.rspbean.BaseData
import com.ewzj.bigdata.mvp.model.rspbean.TokenBean
import com.jess.arms.base.App
import com.jess.arms.mvp.BasePresenter
import com.jess.arms.utils.DataHelper
import com.jess.arms.utils.UiUtils
import com.umeng.socialize.PlatformConfig
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import me.jessyan.rxerrorhandler.core.RxErrorHandler
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject

/**
 * author:zhangjing
 * 作用:
 * return:
 */
class LoginPresenter @Inject constructor(val application: Application, val mRxErrorHandler: RxErrorHandler, view: LoginContract.View, model: LoginContract.Model) : BasePresenter<LoginContract.Model, LoginContract.View>(model, view) {
    lateinit var platform: PlatformConfig.Platform;
    val context = mRootView as Activity
    lateinit var dis: Disposable;
    val authListener=object : UMAuthListener {
        override fun onComplete(p0: SHARE_MEDIA, p1: Int, p2: MutableMap<String, String>) {
            if (p0==SHARE_MEDIA.WEIXIN){
                loginByThrid(p2.get("accessToken")!!, p2.get("openid")!!,p0.name)
            }else{
                loginByThrid(p2.get("accessToken")!!, p2.get("uid")!!,p0.name)
            }
        }

        override fun onCancel(p0: SHARE_MEDIA?, p1: Int) {
            mRootView.dismisdialog()
        }

        override fun onError(p0: SHARE_MEDIA?, p1: Int, p2: Throwable?) {
            mRootView.dismisdialog()
        }

        override fun onStart(p0: SHARE_MEDIA?) {

        }

    }
    fun login(username: String, password: String) {
        if (username.isNullOrEmpty()) {
            UiUtils.SnackbarText(context.getString(R.string.phoneempty))
            return
        }
        if (!RegExpValidatorUtils.IsHandset(username)) {
            UiUtils.SnackbarText(context.getString(R.string.phoneillegal))
            return
        }
        if (password.isNullOrEmpty()) {
            UiUtils.SnackbarText(context.getString(R.string.codeillegal))
            return
        }
        mModel.login(username, password).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : Consumer<BaseData<TokenBean>> {
                    override fun accept(t: BaseData<TokenBean>) {
                        DataHelper.SetStringSF(context,AppKey.API_TOKEN,t.data!!.xtoken)
                        context.finish()
                    }

                }, Consumer { UiUtils.SnackbarText(context.getString(R.string.loginfail)) })
    }

    fun initThirdLogin(platname: SHARE_MEDIA) {
        mRootView.showdialog()
        UMShareAPI.get(context).getPlatformInfo(context, platname, authListener)
    }

    fun sendSms(phone: String) {
        if (phone.isNullOrEmpty()) {
            UiUtils.SnackbarText(context.getString(R.string.phoneempty))
            return
        }
        if (!RegExpValidatorUtils.IsHandset(phone)) {
            UiUtils.SnackbarText(context.getString(R.string.phoneillegal))
            return
        }
        mModel.sendSms(phone).compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object :ErrorHandleSubscriber<BaseData<Any>>(mRxErrorHandler){
                    override fun onNext(t: BaseData<Any>?) {
                        UiUtils.SnackbarText(context.resources.getString(R.string.smssuccess))
                    }
                })
        dis = Observable.interval(1, TimeUnit.SECONDS).compose(RxUtils.bindToLifecycle(mRootView))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Consumer<Long> {
                    override fun accept(along: Long) {
                        if (along < 60) {
                            mRootView.showEnableCode(along)
                        } else {
                            if (dis != null) {
                                dis.dispose()
                            }
                            mRootView.showAbleCode()
                        }
                    }
                })
    }

    fun loginByThrid(token:String,opneid: String,name:String) {
        mModel.loginByThird(token, opneid, name.toLowerCase(), "android").compose(RxUtils.applySchedulers(mRootView))
                .subscribe(object : Consumer<BaseData<TokenBean>> {
                    override fun accept(t: BaseData<TokenBean>) {
                        DataHelper.SetStringSF(context,AppKey.API_TOKEN,t.data?.xtoken)
                        context.finish()
                    }

                }, Consumer { UiUtils.SnackbarText(context.getString(R.string.loginfail)) })

    }
}